# -*- coding: utf-8 -*-

"""
@author: 猿小天
@contact: QQ:1638245306
@Created on: 2021/6/3 003 0:30
@Remark: 同步管理
"""
from dvadmin.system.models import CeleryLog,CeleryResLog
from dvadmin.utils.json_response import SuccessResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin.utils.celery import async_signal
from dvadmin.utils.exception import ErrorResponse
class CelerySerializer(CustomModelSerializer):
    """
    同步脚本-序列化器
    """

    class Meta:
        model = CeleryLog
        fields = "__all__"
        read_only_fields = ["id"]

class CeleryResSerializer(CustomModelSerializer):
    """
    同步脚本-序列化器
    """

    class Meta:
        model = CeleryResLog
        fields = "__all__"
        read_only_fields = ["id"]


class CeleryViewSet(CustomModelViewSet):
    """
    部门管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = CeleryLog.objects.all()
    serializer_class = CelerySerializer

    # extra_filter_backends = []

    # def list(self, request, *args, **kwargs):
    #     queryset = self.filter_queryset(self.get_queryset())
    #     page = self.paginate_queryset(queryset)
    #     if page is not None:
    #         serializer = self.get_serializer(page, many=True, request=request)
    #         return self.get_paginated_response(serializer.data)
    #     serializer = self.get_serializer(queryset, many=True, request=request)
    #     return SuccessResponse(data=serializer.data, msg="获取成功")
    # def create(self, request, *args, **kwargs):
    #     async_signal.send(sender=CeleryLog,data=request.data)
    #     return super().create(request, *args, **kwargs)

    def get_async_data(self, request,pk):
        """
        动态获取关联表的数据
        """
        queryset = CeleryResLog.objects.filter(celery_res_id=pk)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = CeleryResSerializer(page, many=True, request=request)
            return self.get_paginated_response(serializer.data)
        serializer = CeleryResSerializer(queryset, many=True, request=request)
        return SuccessResponse(msg="获取成功", data=queryset, total=len(queryset))
